from PIL import ImageGrab
import pytesseract
import sys
import os
import time

def capture_lower_half_screen():
    """截取屏幕下半部分区域"""
    full_screen = ImageGrab.grab()
    if full_screen is None:
        print("错误：无法获取屏幕截图")
        sys.exit(1)
    
    width, height = full_screen.size
    
    # 计算下半屏区域 (从屏幕中间到底部)
    lower_half_bbox = (0, 2*height//3, width, height)
    lower_half = full_screen.crop(lower_half_bbox)
    
    if lower_half.size[0] == 0 or lower_half.size[1] == 0:
        print("错误：截图区域无效")
        sys.exit(1)
    
    return lower_half

def preprocess_image(image):
    """预处理图像以提高识别率"""
    # 转为灰度
    img = image.convert('L')
    
    # 二值化处理
    threshold = 180
    img = img.point(lambda x: 0 if x < threshold else 255)
    
    # 放大图像提高识别率
    scale_factor = 2
    new_size = (img.width * scale_factor, img.height * scale_factor)
    img = img.resize(new_size, ImageGrab.Image.LANCZOS)
    
    return img

def recognize_chinese_text(image):
    """使用Tesseract识别图像中的中文字符"""
    # 预处理图像
    processed_img = preprocess_image(image)
    
    # 设置Tesseract参数
    config = r'--oem 3 --psm 6 -l chi_sim'
    
    # 执行OCR识别
    text = pytesseract.image_to_string(processed_img, config=config)
    
    return text.strip()

def main():
    screenshot = capture_lower_half_screen()
    result = recognize_chinese_text(screenshot)
    local_time = time.localtime(time.time())
    time_str = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    
    if '奖励' in result:
        result_print = ' 每日委托完成'
    else:
        result_print = ''
    
    print(time_str + result_print)

if __name__ == "__main__":
    main()
